Chapter 2: Strings

TACo about Python logo

Strings

The String Type


Strings are something you have already been using. You just didn't know what they were called.

print("tacos")
This is an example of a String. The String part is:
food = "tacos"
String literal is just a particular String just like a number literal would be something like 7.
print("This is a string"+' so is this.')
You can get the length of a string using len()

Concatenation and Repetition


Let's say you have someone's name is "Marry" and whose last name is "Jane". If I was to add them together what do you think would happen?


Did it do what you thought it would do?
what about if I was to do something like 5 * "Pop..."? What do you think will happen?

Now, it will not allow you to add 10 and "Apples".
This throws an error because you can only concatenate strings. You can get around this by changing the number 10 to a string using str()

What about if I was to do a float like 2.5 and an int 5?

What if I changed x to an Integer then tried it again?

String methods


String methods can be useful for many reasons. For example, let's say you need to compare items and don't know how they will be typed and you don't care about the casing.

 name= "Jeff Owen"
You can change it to just being upper case using .upper() you can also make the whole thing lower case using .lower():
The behavior of an object is given through its methods. A method, like a function, is a collection of programming instructions that carry out a particular task. But unlike a function, which is a standalone operation, a method can only be applied to an object of the type for which it was defined.